"""
请求统计模块
用于收集API Gateway的运行指标
"""
import time
import threading
from collections import deque
from datetime import datetime


class RequestStats:
    """请求统计类"""
    
    def __init__(self):
        # 基础计数器
        self.total_requests = 0
        self.active_requests = 0
        self.completed_requests = 0
        self.failed_requests = 0
        
        # 响应时间统计（最近100个请求）
        self.response_times = deque(maxlen=100)
        
        # 队列长度历史（最近100个采样）
        self.queue_lengths = deque(maxlen=100)
        
        # 线程锁
        self.lock = threading.Lock()
        
        # 启动时间
        self.start_time = time.time()
    
    def on_request_start(self):
        """请求开始"""
        with self.lock:
            self.total_requests += 1
            self.active_requests += 1
            # 记录队列长度（活跃请求数作为队列长度的近似）
            self.queue_lengths.append(self.active_requests)
    
    def on_request_end(self, response_time, success=True):
        """请求结束"""
        with self.lock:
            self.active_requests -= 1
            if success:
                self.completed_requests += 1
            else:
                self.failed_requests += 1
            
            # 记录响应时间
            self.response_times.append(response_time)
    
    def get_stats(self):
        """获取统计数据"""
        with self.lock:
            # 计算平均响应时间
            avg_response_time = 0
            if self.response_times:
                avg_response_time = sum(self.response_times) / len(self.response_times)
            
            # 计算平均队列长度
            avg_queue_length = 0
            if self.queue_lengths:
                avg_queue_length = sum(self.queue_lengths) / len(self.queue_lengths)
            
            # 运行时长
            uptime_seconds = int(time.time() - self.start_time)
            
            # QPS（每秒请求数）
            qps = 0
            if uptime_seconds > 0:
                qps = self.total_requests / uptime_seconds
            
            return {
                'total_requests': self.total_requests,
                'active_requests': self.active_requests,
                'completed_requests': self.completed_requests,
                'failed_requests': self.failed_requests,
                'success_rate': f"{(self.completed_requests / max(1, self.total_requests)) * 100:.2f}%",
                'avg_response_time': f"{avg_response_time:.2f}s",
                'current_queue_length': self.active_requests,
                'avg_queue_length': f"{avg_queue_length:.1f}",
                'qps': f"{qps:.2f}",
                'uptime_seconds': uptime_seconds,
                'uptime_readable': self._format_uptime(uptime_seconds),
                'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
    
    def get_prometheus_metrics(self):
        """获取Prometheus格式的指标"""
        stats = self.get_stats()
        
        metrics = []
        metrics.append(f"# HELP gateway_requests_total Total number of requests")
        metrics.append(f"# TYPE gateway_requests_total counter")
        metrics.append(f"gateway_requests_total {self.total_requests}")
        
        metrics.append(f"# HELP gateway_requests_active Currently active requests")
        metrics.append(f"# TYPE gateway_requests_active gauge")
        metrics.append(f"gateway_requests_active {self.active_requests}")
        
        metrics.append(f"# HELP gateway_queue_length Current queue length (approximation)")
        metrics.append(f"# TYPE gateway_queue_length gauge")
        metrics.append(f"gateway_queue_length {self.active_requests}")
        
        avg_rt = sum(self.response_times) / len(self.response_times) if self.response_times else 0
        metrics.append(f"# HELP gateway_response_time_seconds Average response time")
        metrics.append(f"# TYPE gateway_response_time_seconds gauge")
        metrics.append(f"gateway_response_time_seconds {avg_rt:.2f}")
        
        uptime = int(time.time() - self.start_time)
        metrics.append(f"# HELP gateway_uptime_seconds Gateway uptime in seconds")
        metrics.append(f"# TYPE gateway_uptime_seconds counter")
        metrics.append(f"gateway_uptime_seconds {uptime}")
        
        return "\n".join(metrics) + "\n"
    
    def _format_uptime(self, seconds):
        """格式化运行时长"""
        days = seconds // 86400
        hours = (seconds % 86400) // 3600
        minutes = (seconds % 3600) // 60
        secs = seconds % 60
        
        parts = []
        if days > 0:
            parts.append(f"{days}天")
        if hours > 0:
            parts.append(f"{hours}小时")
        if minutes > 0:
            parts.append(f"{minutes}分钟")
        if secs > 0 or not parts:
            parts.append(f"{secs}秒")
        
        return "".join(parts)


# 全局实例
request_stats = RequestStats()
